using UnityEngine;
using QFramework;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

namespace ProjectSurvivor
{
    public partial class GetAllExp : GamePlayObject
    {
        static IEnumerator FlyToPlayStart()
        {
            IEnumerable<PowerUp> exps = FindObjectsByType<Exp>(FindObjectsInactive.Exclude, FindObjectsSortMode.None);
            IEnumerable<PowerUp> coins = FindObjectsByType<Coin>(FindObjectsInactive.Exclude, FindObjectsSortMode.None);
            int count = 0;
            foreach (var item in exps.Concat(coins).OrderByDescending(e => e.InScreen).ThenBy(e=>e.Distance2D(Player.Default)))
            {
                if (!item.InScreen)
                {
                    
                    if (count > 5)
                    {
                        count = 0;
                        yield return new WaitForEndOfFrame();
                    }
                }
                else
                {
                    if(count>2)
                    {
                        count = 0;
                        yield return new WaitForEndOfFrame();
                    }
                }
                count++;
                ActionKit.OnUpdate.Register(() =>
                {
                    var player = Player.Default;
                    if (player)
                    {
                        item.transform.Translate(player.NormalizedDirection2DFrom(item) * Time.deltaTime * 5f);
                    }
                }).UnRegisterWhenGameObjectDestroyed(item);
            }
        }


        protected override Collider2D Collider2D => SelfCircleCollider2D;
        private void OnTriggerEnter2D(Collider2D collision)
        {
            if (collision.GetComponent<CollectableArea>())
            {
                PowerManager.Default.StartCoroutine(FlyToPlayStart());
                AudioKit.PlaySound("GetAllExp");
                this.DestroyGameObjGracefully();
            }

        }

    }
}
